package com.zmx.doctor.view.activity;


import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.google.gson.Gson;
import com.lcw.library.imagepicker.ImagePicker;
import com.netease.nim.avchatkit.AVChatKit;
import com.netease.nim.avchatkit.activity.AVChatActivity;
import com.netease.nim.avchatkit.model.Accounts;
import com.netease.nim.avchatkit.teamavchat.activity.TeamAVChatActivity;
import com.netease.nim.avchatkit.ui.MyDialog;
import com.netease.nimlib.sdk.NIMClient;
import com.netease.nimlib.sdk.RequestCallback;
import com.netease.nimlib.sdk.avchat.AVChatCallback;
import com.netease.nimlib.sdk.avchat.AVChatManager;
import com.netease.nimlib.sdk.avchat.model.AVChatChannelInfo;
import com.netease.nimlib.sdk.msg.MessageBuilder;
import com.netease.nimlib.sdk.msg.MsgService;
import com.netease.nimlib.sdk.msg.constant.SessionTypeEnum;
import com.netease.nimlib.sdk.msg.model.IMMessage;
import com.netease.nimlib.sdk.uinfo.UserService;
import com.netease.nimlib.sdk.uinfo.model.NimUserInfo;
import com.wang.adapters.interfaceabstract.OnItemClickListener;
import com.zmx.doctor.BaseActivity;
import com.zmx.doctor.R;
import com.zmx.doctor.adapter.ChatMessageAdapter;
import com.zmx.doctor.adapter.RecommendedCasesAdapter;
import com.zmx.doctor.listener.ChatListener;
import com.zmx.doctor.listener.InformUpdateListenerManager;
import com.zmx.doctor.listener.MessageUpdateListener;
import com.zmx.doctor.okhttp.OkHttp3ClientManager;
import com.zmx.doctor.pojo.ChatPatients;
import com.zmx.doctor.pojo.ChatPojo;
import com.zmx.doctor.pojo.MultipartyCallsMessage;
import com.zmx.doctor.pojo.RecommendedCases;
import com.zmx.doctor.utils.AllUtil;
import com.zmx.doctor.utils.BitmapUtil;
import com.zmx.doctor.view.util.GlideLoader;
import com.zmx.doctor.view.util.MySharedPreferences;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.lang.ref.WeakReference;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class OrderDetailsActivity extends BaseActivity {

    @BindView(R.id.rl_view)
    RecyclerView rl_view;
    @BindView(R.id.review)
    RecyclerView review;
    @BindView(R.id.send)
    Button send;
    @BindView(R.id.textView_cases)
    TextView textView_cases;
    @BindView(R.id.toolbar_button)
    Button toolbar_button;
    @BindView(R.id.message)
    EditText message;
    @BindView(R.id.layout)
    RelativeLayout layout;
    @BindView(R.id.add)
    ImageView add;
    @BindView(R.id.phoenix)
    ImageView phoenix;
    @BindView(R.id.iv_video)
    ImageView iv_video;
    @BindView(R.id.prescription)
    ImageView prescription;
    @BindView(R.id.layout_mode)
    LinearLayout layout_mode;
    @BindView(R.id.rl_rootview)
    RelativeLayout rl_rootview;
    private String ask_id, patient_id;
    private String type;

    //    private ChatAdapter chat_adapter;
    private List<ChatPojo> list = new ArrayList<>();

    private ChatMessageAdapter chatMessageAdapter;

    private int is_call = 0;

    private boolean hidden_mobel = false;

    private int REQUEST_SELECT_IMAGES_CODE = 1;
    private String imagePath = "";//本地的图片

    private String medical_id = "";

    private RecommendedCasesAdapter adapter;
    private List<RecommendedCases> lists;

    private String s_name,s_head,tempId;


    @Override
    protected int getLayoutId() {
        return R.layout.activity_order_details;
    }

    @Override
    protected void initViews() {

        ButterKnife.bind(this);
        setToolbar(R.id.tool_bar);
        ask_id = this.getIntent().getStringExtra("ask_id");
        type = this.getIntent().getStringExtra("type");
        patient_id = this.getIntent().getStringExtra("patient_id");
        s_head = this.getIntent().getStringExtra("head");
        tempId = this.getIntent().getStringExtra("temp_id");

        lists = new ArrayList<>();
        adapter = new RecommendedCasesAdapter(mActivity);
        review.setLayoutManager(new LinearLayoutManager(this));
        review.setAdapter(adapter);

        adapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            protected void onItemClick(View view, int listPosition) {

                Bundle bundle = new Bundle();
                bundle.putString("cases_id",lists.get(listPosition).getCases_id()+"");
                startActivity(RecommendedCasesDetailsActivity.class,bundle);

            }
        });


        //接口InformUpdateListener的实现方法，监听数据更新中是否有首页图片更新
        InformUpdateListenerManager informUpdateListenerManager = new InformUpdateListenerManager(mActivity);
        informUpdateListenerManager.getInstance(mActivity).setChatListener(new MyInformUpdateListener(mActivity));

        rl_rootview.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {

                int heightDiff = rl_rootview.getRootView().getHeight() - rl_rootview.getHeight();
                if (heightDiff > dpToPx(mActivity, 200)) {
                    // ... do something here
                    Log.e("----------", "打开");

                    hidden_mobel = false;
                    layout_mode.setVisibility(View.GONE);

                } else {
                    Log.e("----------", "关闭");

                }

            }
        });


        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        rl_view.setLayoutManager(linearLayoutManager);

        if (Integer.parseInt(type) == 1){

            getData();

        }else {

            getDatas();

        }



    }

    public float dpToPx(Context context, float valueInDp) {
        DisplayMetrics metrics = context.getResources().getDisplayMetrics();
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, valueInDp, metrics);
    }

    public SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {

                case 1:

                    Log.e("设计费", "发顺丰" + msg.obj.toString());

                    try {

                        Gson gson = new Gson();
                        JSONObject object = new JSONObject(msg.obj.toString());
                        JSONObject jsonObject = object.getJSONObject("data");
                        JSONObject ask = jsonObject.getJSONObject("ask");
                        JSONObject patient = jsonObject.getJSONObject("patient");
                        String sex = "";
                        if (patient.getString("sex").equals("1")) {
                            sex = "男";
                        } else {
                            sex = "女";
                        }
                        String birthday = null;
                        try {

                            SimpleDateFormat s = new SimpleDateFormat("yyyyMMdd");
                            birthday = AllUtil.getAgeByBirth(s.parse(patient.getString("birthday"))) + "岁";
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                        is_call = ask.getInt("is_call");

                        // 字符串转数组  java.lang.String
                        JSONArray imgs = ask.getJSONArray("picture");
                        List<String> image_url = new ArrayList<>();
                        for (int i = 0; i < imgs.length(); i++) {

                            JSONObject object1 = imgs.getJSONObject(i);
                            image_url.add(object1.getString("imgUrl"));

                        }

                        ChatPojo cpj = new ChatPojo();
                        ChatPatients cp = new ChatPatients();
                        cp.setContext(ask.getString("content"));
                        cp.setName("基本信息：" + patient.getString("name") + " | " + sex + " | " + birthday + " | " + patient.getString("weight") + "kg");
                        cp.setImageUrl(image_url);
                        s_name = patient.getString("name");
                        cpj.setRole(0);
                        cpj.setChatPatients(cp);
                        list.add(cpj);


                        // 字符串转数组  java.lang.String
                        JSONArray chats = jsonObject.getJSONArray("list");
                        for (int i = 0; i < chats.length(); i++) {

                            JSONObject object1 = chats.getJSONObject(i);

                            ChatPojo c = gson.fromJson(object1.toString(), ChatPojo.class);

                            list.add(c);

                        }

                        info();

                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("图径", "" + e.toString());
                    }
                    break;

                case 2:

                    try {

                        Log.e("类型", "类型" + msg.obj.toString());
                        JSONObject object = new JSONObject(msg.obj.toString());
                        if (object.getInt("code") == 1) {

                            JSONObject data = object.getJSONObject("data");

                            ChatPojo cp = new ChatPojo();
                            cp.setName(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.name, ""));
                            cp.setReplytime(simpleDateFormat.format(new Date()));
                            cp.setAvatar(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.avatar, ""));
                            if (data.getInt("type") == 0) {

                            cp.setContent(message.getText().toString());

                            } else if (data.getInt("type") == 1) {

                            cp.setContent(imagePath);

                            }
                            cp.setType(data.getInt("type"));
                            cp.setRole(data.getInt("role"));
                            list.add(cp);
                            message.setText("");
                            info();
                        }

                        Toast(object.getString("msg"));

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 3:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));

                        if (object.getInt("code") == 1) {

                            JSONObject data = object.getJSONObject("data");
                            String toAccount = data.getString("join_member_id");

                            NimUserInfo user = NIMClient.getService(UserService.class).getUserInfo(toAccount);

                            if (user == null) {

                                String[] array = {toAccount};
                                List<String> accounts = Arrays.asList(array);

                                NIMClient.getService(UserService.class).fetchUserInfo(accounts)
                                        .setCallback(new RequestCallback<List<NimUserInfo>>() {
                                            @Override
                                            public void onSuccess(List<NimUserInfo> nimUserInfos) {
                                                if (!nimUserInfos.isEmpty()) {
                                                    NimUserInfo nimUserInfo = nimUserInfos.get(0);

                                                    AVChatKit.outgoingCall(mActivity, nimUserInfo.getAccount(), nimUserInfo.getName(), 2, AVChatActivity.FROM_INTERNAL, Integer.parseInt(ask_id), Integer.parseInt(patient_id), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.role, ""), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.password, ""));
                                                } else {
                                                    Toast.makeText(mActivity, "请检查对方账号是否存在！", Toast.LENGTH_SHORT).show();
                                                }

                                            }

                                            @Override
                                            public void onFailed(int i) {
                                                Log.e("RTSActivity", "onFailed: 获取云端好友资料失败,错误码：" + i);
                                            }

                                            @Override
                                            public void onException(Throwable throwable) {

                                            }
                                        });
                            } else {

                                AVChatKit.outgoingCall(mActivity, user.getAccount(), user.getName(), 2, AVChatActivity.FROM_INTERNAL, Integer.parseInt(ask_id), Integer.parseInt(patient_id), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.role, ""), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.password, ""));

                            }

                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;

                case 4:

                    try {

                        ArrayList<Accounts> as = new ArrayList<>();
                        Gson gson = new Gson();
                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));

                        if (object.getInt("code") == 1) {

                            JSONArray array = object.getJSONArray("data");

                            ArrayList<String> accounts = new ArrayList<>();
                            for (int i = 0; i < array.length(); i++) {

                                Accounts acs = gson.fromJson(array.get(i).toString(),Accounts.class);
                                as.add(acs);
                                accounts.add(acs.getJoin_member_id());
                            }

                            MultipartyCallsMessage mcm = new MultipartyCallsMessage();
                            mcm.setRoomID(roomID + "");
                            mcm.setMessage_type("1");
                            mcm.setAccounts(as);
                            String mcm_message = gson.toJson(mcm);

                            AVChatManager.getInstance().createRoom(roomID + "", "家属", new AVChatCallback<AVChatChannelInfo>() {
                                @Override
                                public void onSuccess(AVChatChannelInfo avChatChannelInfo) {

                                    Log.e("成功", "成功");

                                    for (String s : accounts) {

                                        // 以单聊类型为例
                                        SessionTypeEnum sessionType = SessionTypeEnum.P2P;
                                        // 创建一个文本消息
                                        IMMessage textMessage = MessageBuilder.createTextMessage(s, sessionType, mcm_message);
                                        // 发送给对方
                                        NIMClient.getService(MsgService.class).sendMessage(textMessage, false);

                                    }

                                    AVChatKit.outgoingTeamCall(mActivity, 0, true, "1", roomID + "", as, "多方通话", Integer.parseInt(ask_id), Integer.parseInt(patient_id), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.role, ""), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.password, ""));

                                }

                                @Override
                                public void onFailed(int code) {

                                    Log.e("错误码", "错误码" + code);
                                    if (code == 417) {

                                        for (String s : accounts) {

                                            // 以单聊类型为例
                                            SessionTypeEnum sessionType = SessionTypeEnum.P2P;
                                            // 创建一个文本消息
                                            IMMessage textMessage = MessageBuilder.createTextMessage(s, sessionType, mcm_message);
                                            // 发送给对方
                                            NIMClient.getService(MsgService.class).sendMessage(textMessage, false);

                                        }

                                        AVChatKit.outgoingTeamCall(mActivity, 0, true, "1", roomID + "", as, "多方通话", Integer.parseInt(ask_id), Integer.parseInt(patient_id), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.role, ""), MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.password, ""));

                                    }

                                }

                                @Override
                                public void onException(Throwable exception) {

                                    Log.e("错误提示", "错误提示" + exception.toString());
                                }
                            });


                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 5:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast(object.getString("msg"));

                        if (object.getInt("code") == 1){

                            ChatPojo cp = new ChatPojo();
                            cp.setName(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.name, ""));
                            cp.setReplytime(simpleDateFormat.format(new Date()));
                            cp.setAvatar(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.avatar, ""));
                            cp.setType(2);
                            cp.setContent(temp_id);
                            cp.setRole(2);
                            list.add(cp);
                            info();

                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 6:

                    ChatPojo cp = new ChatPojo();
                    cp.setName(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.name, ""));
                    cp.setReplytime(simpleDateFormat.format(new Date()));
                    cp.setAvatar(MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.avatar, ""));
                    cp.setType(2);
                    cp.setRole(2);
                    cp.setContent(temp_id);
                    list.add(cp);
                    info();

                    break;

                case 7:

//                    isMedical();
                    Bundle bundle = new Bundle();
                    bundle.putString("ask_id",ask_id);
                    bundle.putString("patient_id",patient_id);
                    startActivity(PatientsCasesActivity.class,bundle);

                    break;

                case 8:

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        int type = object.getInt("code");

                        View view = getLayoutInflater().inflate(com.netease.nim.avchatkit.R.layout.dialog, null);
                        MyDialog mMyDialog = new MyDialog(mActivity, 0, 0, view, com.netease.nim.avchatkit.R.style.DialogTheme);
                        mMyDialog.setCancelable(true);

                        EditText main_suit = view.findViewById(com.netease.nim.avchatkit.R.id.main_suit);
                        EditText now_medical_history = view.findViewById(com.netease.nim.avchatkit.R.id.now_medical_history);
                        EditText past_medical_history = view.findViewById(com.netease.nim.avchatkit.R.id.past_medical_history);
                        EditText genetic = view.findViewById(com.netease.nim.avchatkit.R.id.genetic);
                        EditText allergy = view.findViewById(com.netease.nim.avchatkit.R.id.allergy);
                        TextView regular = view.findViewById(com.netease.nim.avchatkit.R.id.regular);
                        regular.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                showList(regular);
                            }
                        });

                        TextView notice = view.findViewById(com.netease.nim.avchatkit.R.id.notice);
                        notice.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                showNotice(notice);
                            }
                        });
                        if (type == 1){

                            JSONObject data = object.getJSONObject("data");
                            main_suit.setText(data.getString("sketch"));
                            now_medical_history.setText(data.getString("now"));
                            past_medical_history.setText(data.getString("history"));
                            genetic.setText(data.getString("family"));
                            allergy.setText(data.getString("allergy"));
                            regular.setText(data.getString("marry"));
                            notice.setText(data.getString("birthday"));
                            medical_id = data.getString("id");
                        }

                        ImageView image_back = view.findViewById(com.netease.nim.avchatkit.R.id.image_back);
                        image_back.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                mMyDialog.dismiss();
                            }
                        });

                        Button submit = view.findViewById(com.netease.nim.avchatkit.R.id.submit);
                        submit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {


                                if (type == 0){

                                    addMedical(main_suit.getText().toString(),past_medical_history.getText().toString(),allergy.getText().toString(),now_medical_history.getText().toString(),genetic.getText().toString(),regular.getText().toString(),notice.getText().toString());

                                }else{

                                    editMedical(main_suit.getText().toString(),past_medical_history.getText().toString(),allergy.getText().toString(),now_medical_history.getText().toString(),genetic.getText().toString(),medical_id,regular.getText().toString(),notice.getText().toString());

                                }

                            }
                        });

                        mMyDialog.show();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }


                    break;

                case 9:
                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Toast.makeText(mActivity,object.getString("msg"), Toast.LENGTH_SHORT).show();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    break;

                case 10:


                    try {

                        JSONObject jsonObject = new JSONObject(msg.obj.toString());


                        if (jsonObject.getInt("code") == 1){

                            Bundle bundles = new Bundle();
                            bundles.putString("name",s_name);
                            bundles.putString("head",s_head);
                            bundles.putString("p_id",patient_id);
                            bundles.putString("data",jsonObject.getString("data"));
                            startActivity(PulseConditionActivity.class,bundles);

                        }else{

                            Toast(jsonObject.getString("msg"));

                        }


                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

                case 11:

                    lists.clear();

                    try {

                        JSONObject object = new JSONObject(msg.obj.toString());
                        Gson gson = new Gson();

                        if (!object.isNull("data")) {

                            textView_cases.setVisibility(View.VISIBLE);
                            JSONArray array = object.getJSONArray("data");
                            for (int i = 0;i<array.length();i++){

                                RecommendedCases doctor = gson.fromJson(array.getJSONObject(i).toString(),RecommendedCases.class);
                                lists.add(doctor);

                            }

                            adapter.setListAndNotifyDataSetChanged(lists);

                        }



                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    break;

            }

        }
    };

    // 更新显示listview
    public void info() {

        if (chatMessageAdapter == null) {

            chatMessageAdapter = new ChatMessageAdapter(this, list,mActivity,handler,1);
            rl_view.setAdapter(chatMessageAdapter);

        } else {

            chatMessageAdapter.notifyDataSetChanged();
            rl_view.smoothScrollToPosition(list.size());

        }

    }



    //获取病例
    public void isMedical(){

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        ls.add(patient_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "isMedical");
        params.put("data[ask_id]", ask_id);
        params.put("data[patient_id]", patient_id);
        com.netease.nim.avchatkit.okhttp.OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/doctor/", params, handler, 8, 404);
    }


    /**
     * 获取所有提问
     */
    public void getData() {

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        ls.add(patient_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "patientAskRecord");
        params.put("data[ask_id]", ask_id);
        params.put("data[patient_id]", patient_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 1, 404);

    }


    /**
     * 获取所有提问
     */
    public void send(String message, String type) {

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        ls.add(message);
        ls.add(type);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "patientAskReply");
        params.put("data[ask_id]", ask_id);
        params.put("data[content]", message);
        params.put("data[type]", type);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/app/", params, handler, 2, 404);

    }

    /**
     * 获取所有提问
     */
    public void sends(String message, String type) {

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        ls.add(message);
        ls.add(type);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "replyAsk");
        params.put("data[ask_id]", ask_id);
        params.put("data[content]", message);
        params.put("data[type]", type);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.team/entry", params, handler, 2, 404);

    }

    public void addMedical(String sketch,String history,String allergy,String now,String family,String regular,String notice) {

        List<String> ls = new ArrayList<>();
        ls.add(allergy);
        ls.add(ask_id);
        ls.add(notice);
        ls.add(family);
        ls.add(history);
        ls.add(regular);
        ls.add(now);
        ls.add(patient_id);
        ls.add(sketch);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "addMedical");
        params.put("data[ask_id]", ask_id);
        params.put("data[patient_id]", patient_id);
        params.put("data[sketch]", sketch);
        params.put("data[history]", history);
        params.put("data[allergy]", allergy);
        params.put("data[now]", now);
        params.put("data[family]", family);
        params.put("data[marry]", regular);
        params.put("data[birthday]", notice);
        com.netease.nim.avchatkit.okhttp.OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/doctor/", params, handler, 9, 404);
    }


    public void editMedical(String sketch,String history,String allergy,String now,String family,String medical_id,String regular,String notice) {

        List<String> ls = new ArrayList<>();
        ls.add(allergy);
        ls.add(ask_id);
        ls.add(notice);
        ls.add(family);
        ls.add(history);
        ls.add(regular);
        ls.add(medical_id);
        ls.add(now);
        ls.add(patient_id);
        ls.add(sketch);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "editMedical");
        params.put("data[ask_id]", ask_id);
        params.put("data[patient_id]", patient_id);
        params.put("data[sketch]", sketch);
        params.put("data[history]", history);
        params.put("data[allergy]", allergy);
        params.put("data[now]", now);
        params.put("data[family]", family);
        params.put("data[marry]", regular);
        params.put("data[medical_id]", medical_id);
        params.put("data[birthday]", notice);
        com.netease.nim.avchatkit.okhttp.OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/doctor/", params, handler, 9, 404);
    }


    /**
     * 获取网易云的token
     */
    public void getAskToken(int type, int what) {

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        ls.add(is_call + "");
        ls.add(type + "");
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getAskToken");
        params.put("data[ask_id]", ask_id);
        params.put("data[line]", type);
        params.put("data[is_call]", is_call);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/doctor/", params, handler, what, 404);

    }

    public void postMake(String temp_id) {

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        ls.add(patient_id);
        ls.add(temp_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "postMake");
        params.put("data[ask_id]", ask_id);
        params.put("data[patient_id]", patient_id);
        params.put("data[temp_id]", temp_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.make/entry", params, handler, 5, 404);

    }


    public void postMakes(String temp_id) {

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        ls.add(patient_id);
        ls.add(temp_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "tramPostMake");
        params.put("data[ask_id]", ask_id);
        params.put("data[patient_id]", patient_id);
        params.put("data[temp_id]", temp_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.team/entry", params, handler, 5, 404);

    }

    private int roomID = 709394;

    @OnClick({R.id.send, R.id.add,R.id.iv_video, R.id.phoenix, R.id.prescription,R.id.toolbar_button})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.send:


                if (message.getText().toString().equals("")) {
                    Toast("请输入内容");
                    return;
                }
                if (Integer.parseInt(type) == 1){

                    send(message.getText().toString(), "0");
                }else{
                    sends(message.getText().toString(), "0");
                }

                break;

            case R.id.add:

                if (hidden_mobel) {

                    hidden_mobel = false;
                    layout_mode.setVisibility(View.GONE);

                } else {

                    hideSoftKeyboard(mActivity);
                    hidden_mobel = true;
                    layout_mode.setVisibility(View.VISIBLE);
                    getCases();

                }

                break;

            case R.id.phoenix:

                ImagePicker.getInstance()
                        .setTitle("标题")//设置标题
                        .showCamera(true)//设置是否显示拍照按钮
                        .showImage(true)//设置是否展示图片
                        .showVideo(false)//设置是否展示视频
                        .setSingleType(true)//设置图片视频不能同时选择
                        .setMaxCount(1)//设置最大选择图片数目(默认为1，单选)
                        .setImageLoader(new GlideLoader())//设置自定义图片加载器
                        .start(mActivity, REQUEST_SELECT_IMAGES_CODE);//REQEST_SELECT_IMAGES_CODE为Intent调用的requestCode

                break;

            case R.id.prescription:

                Bundle bundle = new Bundle();
                bundle.putString("logo", "1");
                bundle.putString("ask_id", ask_id);
                bundle.putString("p_id", patient_id);
                bundle.putString("type", type);
                bundle.putString("temp_id", tempId);
                startActivity(PrescriptionMouldActivity.class, bundle, 2);

                break;

            case R.id.iv_video:

                if (is_call == 1) {

                    getAskToken(2, 4);//多方通话

                } else {

                    getAskToken(1, 3);

                }

                break;

            case R.id.toolbar_button:
                getPulesStatus();
                break;

        }
    }


    private static String temp_id;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {

        if (requestCode == REQUEST_SELECT_IMAGES_CODE && resultCode == RESULT_OK) {

            List<String> imagePaths = data.getStringArrayListExtra(ImagePicker.EXTRA_SELECT_IMAGES);

            for (String s : imagePaths) {

                if (!s.equals("") && s != null) {

                    imagePath = s;
                    upload(imagePath);

                }

            }

        } else if (requestCode == 2 && resultCode == RESULT_OK) {

            temp_id = data.getExtras().getString("temp_id");

            if (Integer.parseInt(type) == 1){

                postMake(temp_id);

            }else {

                postMakes(temp_id);

            }



        }
    }


    public static void hideSoftKeyboard(Activity activity) {
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    private void upload(String url) {// selImageList 包含图片路径的list


        OkHttpClient okHttpClient = new OkHttpClient();

        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM); //表单上传文件

        File file = new File(new BitmapUtil().compressImage(url)); //根据路径创建file对象
        builder.addFormDataPart("image[]", //
                file.getName(),
                RequestBody.create(MediaType.parse("image/jpeg"), file)
        );

        RequestBody requestBody = builder.build();
        Request request = new Request.Builder()
                .url("http://zmx.123xk.cn/admin/api.doctor/AddImg")
                .post(requestBody)
                .build();

        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e("onFailure: ", e.toString());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {

                try {

                    JSONObject object = new JSONObject(response.body().string());
                    JSONObject data = object.getJSONObject("data");

                    if (object.getString("code").equals("1")) {

                        JSONArray array = data.getJSONArray("url");

                        for (int i = 0; i < array.length(); i++) {

                            Log.e("所发生的", "法大师傅" + array.get(i).toString());

                            if (Integer.parseInt(type) == 1){

                                send(array.get(i).toString(), "1");

                            }else{

                                sends(array.get(i).toString(), "1");

                            }

                            imagePath = array.get(i).toString();

                        }


                    } else {
                        Toast(object.getString("msg"));
                    }

                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });

    }


    //静态内部类实现接口监听
    class MyInformUpdateListener implements ChatListener {
        private WeakReference<Activity> mWeakReference;
        public MyInformUpdateListener(Activity activity){
            Log.e("有消息进来了1","有消息进来了1");
            mWeakReference = new WeakReference<Activity>(activity);//使用弱引用引用外部Activity对象
        }

        @Override
        public void updateMessage(String t_id) {

            Log.e("有消息进来了","有消息进来了"+t_id);
            temp_id = t_id;
            handler.sendEmptyMessage(6);

        }
    }

    private AlertDialog alertDialog1; //信息框
    public void showList(TextView textView) {

        final String[] items = {"已婚", "未婚"};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(mActivity);
        alertBuilder.setTitle("请选择");
        alertBuilder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                textView.setText(items[i]);
                alertDialog1.dismiss();
            }
        });
        alertDialog1 = alertBuilder.create();
        alertDialog1.show();
    }
    public void showNotice(TextView textView) {
        final String[] items = {"未生", "一胎", "二胎"};
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(mActivity);
        alertBuilder.setTitle("请选择");
        alertBuilder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                textView.setText(items[i]);
                alertDialog1.dismiss();
            }
        });
        alertDialog1 = alertBuilder.create();
        alertDialog1.show();
    }

    /**
     * 检测脉象
     */
    public void getPulesStatus() {

        List<String> ls = new ArrayList<>();
        ls.add("5");
        ls.add(patient_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getPulesStatus");
        params.put("data[patient_id]", patient_id);
        params.put("data[minute]", "5");
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/watch", params, handler, 10, 404);

    }

    /**
     * 推荐
     */
    public void getCases() {

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        ls.add(patient_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "getCases");
        params.put("data[ask_id]", ask_id);
        params.put("data[patient_id]", patient_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/doctor", params, handler, 11, 404);

    }


    public void getDatas() {

        List<String> ls = new ArrayList<>();
        ls.add(ask_id);
        ls.add(patient_id);
        //请求网络
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("sign", AllUtil.md5(sing(ls)));
        params.put("token", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.token, ""));
        params.put("uid", MySharedPreferences.getInstance(mActivity).getString(MySharedPreferences.uid, ""));
        params.put("ts", System.currentTimeMillis() / 1000); // 当前时间戳
        params.put("cmd", "teamRecord");
        params.put("data[patient_id]", patient_id);
        params.put("data[ask_id]", ask_id);
        OkHttp3ClientManager.getInstance().NetworkRequestMode("http://zmx.123xk.cn/admin/api.team/entry", params, handler, 1, 404);

    }


}

